package com.hjj.controller;

import com.hjj.beans.DictionaryValue;
import com.hjj.dto.ResultDTO;
import com.hjj.exception.CRUDException;
import com.hjj.exception.DataVerificationException;
import com.hjj.services.DictionaryValueServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Locale;

@RestController
@RequestMapping("/DictionaryValue")
public class DictionaryValueController {
    @Autowired
    DictionaryValueServices dictionaryValueServices;

    @Autowired
    MessageSource messageSource;


    @RequestMapping("getAll.action")
    public ArrayList<DictionaryValue> getAll(){
        return dictionaryValueServices.getAll();
    }

    @RequestMapping("add.action")
    public ResultDTO add(@Valid DictionaryValue dictionaryValue, BindingResult bindingResult) throws DataVerificationException, CRUDException {
        if (bindingResult.hasErrors()){
            //获取消息的键
            String message = bindingResult.getFieldError().getDefaultMessage();
            throw new DataVerificationException(messageSource.getMessage(message, null, Locale.getDefault()));
        }

        boolean add = dictionaryValueServices.add(dictionaryValue);

        if (!add) throw new CRUDException("字典值数据添加失败");

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);
        return resultDTO;
    }

    @RequestMapping("editBefore.action")
    public DictionaryValue editBefore(String id){
        return dictionaryValueServices.get(id);
    }

    @RequestMapping("edit.action")
    public ResultDTO edit(@Valid DictionaryValue dictionaryValue, BindingResult bindingResult) throws DataVerificationException, CRUDException {
        if (bindingResult.hasErrors()){
            //获取消息的键
            String message = bindingResult.getFieldError().getDefaultMessage();
            throw new DataVerificationException(messageSource.getMessage(message, null, Locale.getDefault()));
        }

        boolean edit = dictionaryValueServices.edit(dictionaryValue);

        if (!edit) throw new CRUDException("字典值数据修改失败");

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);
        return resultDTO;
    }

    @RequestMapping("del.action")
    public ResultDTO del(@RequestBody String[] ids) throws CRUDException {
        boolean del = dictionaryValueServices.del(ids);

        if (!del) throw new CRUDException("字典值数据删除失败");

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);
        return resultDTO;
    }
}
